<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="title" label="标题" required>
				<uni-easyinput placeholder="新闻标题欧慧群" v-model="formData.title"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="content" label="新闻内容" required>
				<view class="page-body">
					<view class='wrapper'>
						<view class='toolbar' @tap="format" style="height: 120px;overflow-y: auto;">
							<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu"
								data-name="bold"></view>
							<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti"
								data-name="italic"></view>
							<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian"
								data-name="underline"></view>
							<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian"
								data-name="strike"></view>
							<!-- #ifndef MP-BAIDU -->
							<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi"
								data-name="align" data-value="left"></view>
							<!-- #endif -->
							<view :class="formats.align === 'center' ? 'ql-active' : ''"
								class="iconfont icon-juzhongduiqi" data-name="align" data-value="center"></view>
							<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi"
								data-name="align" data-value="right"></view>
							<view :class="formats.align === 'justify' ? 'ql-active' : ''"
								class="iconfont icon-zuoyouduiqi" data-name="align" data-value="justify"></view>
							<!-- #ifndef MP-BAIDU -->
							<view :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height"
								data-name="lineHeight" data-value="2"></view>
							<view :class="formats.letterSpacing ? 'ql-active' : ''"
								class="iconfont icon-Character-Spacing" data-name="letterSpacing" data-value="2em">
							</view>
							<view :class="formats.marginTop ? 'ql-active' : ''"
								class="iconfont icon-722bianjiqi_duanqianju" data-name="marginTop" data-value="20px">
							</view>
							<view :class="formats.marginBottom ? 'ql-active' : ''"
								class="iconfont icon-723bianjiqi_duanhouju" data-name="marginBottom" data-value="20px">
							</view>
							<!-- #endif -->

							<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>

							<!-- #ifndef MP-BAIDU -->
							<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font"
								data-name="fontFamily" data-value="Pacifico"></view>
							<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize"
								data-name="fontSize" data-value="24px"></view>
							<!-- #endif -->
							<view :class="formats.color === '#0000ff' ? 'ql-active' : ''"
								class="iconfont icon-text_color" data-name="color" data-value="#0000ff"></view>
							<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
								class="iconfont icon-fontbgcolor" data-name="backgroundColor" data-value="#00ff00">
							</view>
							<view class="iconfont icon-date" @tap="insertDate"></view>
							<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
							<view :class="formats.list === 'ordered' ? 'ql-active' : ''"
								class="iconfont icon-youxupailie" data-name="list" data-value="ordered"></view>
							<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie"
								data-name="list" data-value="bullet"></view>

							<view class="iconfont icon-undo" @tap="undo"></view>
							<view class="iconfont icon-redo" @tap="redo"></view>

							<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
							<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
							<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
							<view class="iconfont icon-charutupian" @tap="insertImage"></view>
							<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1"
								data-name="header" :data-value="1"></view>
							<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao"
								data-name="script" data-value="sub"></view>
							<view :class="formats.script === 'super' ? 'ql-active' : ''"
								class="iconfont icon-zitishangbiao" data-name="script" data-value="super"></view>

							<view class="iconfont icon-shanchu" @tap="clear"></view>

							<view :class="formats.direction === 'rtl' ? 'ql-active' : ''"
								class="iconfont icon-direction-rtl" data-name="direction" data-value="rtl"></view>
						</view>

						<view class="editor-wrapper">
							<editor id="editor" class="ql-container" placeholder="开始输入..." show-img-size
								show-img-toolbar show-img-resize @statuschange="onStatusChange" :read-only="readOnly"
								@ready="onEditorReady"></editor>
						</view>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="excerpt" label="新闻摘录">
				<uni-easyinput placeholder="新闻摘录" v-model="formData.excerpt"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="cover" label="封面大图" required>
				<uni-file-picker file-mediatype="image" file-extname="jpg,png" return-type="object"
					v-model="formData.cover"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="publish_date" label="发表时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.publish_date"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="last_modify_date" label="最后修改时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.last_modify_date"></uni-datetime-picker>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/New1.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'New1';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			let formData = {
				"title": "",
				"content": "",
				"excerpt": "",
				"cover": null,
				"publish_date": null,
				"last_modify_date": null
			}
			return {
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				},
				formats: {},
				readOnly: false,
				editorCtx: null
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules);
		},
		methods: {
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				});
				this.getEditorContent().then((content) => {
					this.formData.content = content;
					this.$refs.form.validate().then((res) => {
						return this.submitForm(res);
					}).catch(() => {}).finally(() => {
						uni.hideLoading();
					});
				});
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 确保 value 对象包含新闻内容字段
				if (!value.content) {
					value.content = this.formData.content;
				}
				return db.collection(dbCollectionName).add(value)
					.then((res) => {
						uni.showToast({
							title: '新增成功'
						});
						this.getOpenerEventChannel().emit('refreshData');
						setTimeout(() => uni.navigateBack(), 500);
					})
					.catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						});
					});
			},
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context;
					if (this.formData.content) {
						this.editorCtx.setContents({
							html: this.formData.content
						});
					}
				}).exec();
			},
			onStatusChange(e) {
				this.formats = e.detail;
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset;
				if (!name) return;
				this.editorCtx.format(name, value);
			},
			removeFormat() {
				this.editorCtx.removeFormat();
			},
			insertDate() {
				const date = new Date().toLocaleDateString();
				this.editorCtx.insertText({
					text: ` ${date} `
				});
			},
			insertDivider() {
				this.editorCtx.insertDivider();
			},
			insertImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const filePath = res.tempFilePaths[0];
						// 生成一个唯一的文件名，例如使用当前时间戳
						const cloudPath = `images/${Date.now()}.jpg`;

						// 上传图片到云存储
						uniCloud.uploadFile({
							cloudPath,
							filePath,
							success: (uploadRes) => {
								if (uploadRes.fileID) {
									if (this.editorCtx) {
										this.editorCtx.insertImage({
											src: uploadRes.fileID,
											alt: '图像',
											success: function() {
												console.log('insert image success');
											}
										});
									}
								} else {
									console.error('上传图片失败:', uploadRes.errMsg);
									uni.showToast({
										title: '上传图片失败',
										icon: 'none'
									});
								}
							},
							fail: (err) => {
								console.error('上传图片失败:', err);
								uni.showToast({
									title: '上传图片失败',
									icon: 'none'
								});
							}
						});
					}
				});
			},
			undo() {
				this.editorCtx.undo();
			},
			redo() {
				this.editorCtx.redo();
			},
			clear() {
				this.editorCtx.clear();
			},
			getEditorContent() {
				return new Promise((resolve) => {
					this.editorCtx.getContents({
						success: (res) => {
							resolve(res.html);
						}
					});
				});
			}
		}
	}
</script>

<style>
	@import "@/static/editor-icon.css";

	.page-body {
		height: calc(100vh - var(--window-top) - var(--status-bar-height));
	}

	.wrapper {
		height: 100%;
	}

	.editor-wrapper {
		height: calc(100vh - var(--window-top) - var(--status-bar-height) - 140px);
		background: #fff;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}

	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		min-height: 30vh;
		height: 100%;
		margin-top: 20px;
		font-size: 16px;
		line-height: 1.5;
	}

	.ql-active {
		color: #06c;
	}
</style>